package sliver.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import sliver.action.account.AdvertiserLoginAction;
import sliver.action.account.ToLoginAction;
import sliver.entity.Advertiser;
import sliver.service.AdvertiserAccountManager;
import sliver.service.impl.AccountManagerImpl;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class AdvertiserLoginInterceptor extends AbstractInterceptor{

	private static final long serialVersionUID = -44122275055238939L;

	private AdvertiserAccountManager advertiserAccountManager = new AccountManagerImpl();
	
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		
		Class<?> actionClass = invocation.getAction().getClass();
		
		if((actionClass.getName().startsWith("sliver.action.advertisement") || 
				actionClass == ToLoginAction.class) && 
				actionClass != AdvertiserLoginAction.class ){
			
			HttpSession session = ServletActionContext.getRequest().getSession();
			
			if(session.getAttribute("login_advertiser") != null){
				return invocation.invoke();
			}else{
				Cookie[] cookies = ServletActionContext.getRequest().getCookies();
				if(cookies != null){
					for(Cookie cookie : cookies){
						String key = cookie.getName();
						if("cookie_advertiser_username_password".equals(key)){
							String auth = cookie.getValue();
							String[] parts = auth.split("\\|");
							String username = parts[0];
							String password = parts[1];
							
							Advertiser advertiser = advertiserAccountManager.advertiserLogin(username, password);
							
							if(advertiser != null){
								session.setAttribute("login_advertiser", advertiser);
								return invocation.invoke();
							}
						}
					}
				}
			}
		}
		
		return "advertiser_login";
	}

}
